package flexconsole.model {
	import flash.display.NativeWindow;
	import flash.events.EventDispatcher;
	import flash.events.NativeWindowBoundsEvent;
	
	import mx.events.PropertyChangeEvent;
	
	/**
	 *
	 *  @eventType mx.events.PropertyChangeEvent.PROPERTY_CHANGE
	 */
	[Event(name="propertyChange", type="mx.events.PropertyChangeEvent")]
	
	public class WindowStateModel extends EventDispatcher {
		
		
		[Bindable]
		public var x:Number = 0;
		
		[Bindable]
		public var y:Number = 0;
		
		[Bindable]
		public var width:Number = 640;
		
		[Bindable]
		public var height:Number = 480;
		
		private var _target:NativeWindow;
		
		public function WindowStateModel(value:Object = null, target:NativeWindow = null) {
			super();
			if (value) {
				read(value);
			}
			if (target) {
				this.target = target;
			}
		}
		
		public function get target():NativeWindow {
			return _target;
		}
		
		public function set target(window:NativeWindow):void {
			disableTargetListeners();
			_target = window;
			enableTargetListeners();
		}
		
		public function updateTarget():void {
			if (target) {
				disableTargetListeners();
				target.x = x;
				target.y = y;
				target.width = width;
				target.height = height;
				enableTargetListeners();
			}
		}
		
		public function write():Object {
			return { x: x, y: y, width: width, height: height };
		}
		
		public function read(value:Object):void {
            var properties:Array = [ "x", "y", "width", "height" ];
            var n:String;
            
            for each (n in properties) {
                if (value.hasOwnProperty(n)) {
                    this[n] = value[n];
                } else {
                    throw new Error("value does not have property: " + n);
                }
            }
		}
		
		protected function disableTargetListeners():void {
			if (target) {
				target.removeEventListener(NativeWindowBoundsEvent.MOVE, onNativeWindowBounds);
				target.removeEventListener(NativeWindowBoundsEvent.RESIZE, onNativeWindowBounds);
			}
		}
		
		protected function enableTargetListeners():void {
			if (target) {
				target.addEventListener(NativeWindowBoundsEvent.MOVE, onNativeWindowBounds);
                target.addEventListener(NativeWindowBoundsEvent.RESIZE, onNativeWindowBounds);
			}
		}
		
		protected function onNativeWindowBounds(event:NativeWindowBoundsEvent):void {
			read(target);
		}
		
	
	}
}